import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'dart:math' as math;

class ScrollToIndexDemoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ScrollToIndexDemoPageState();
  }
}

class ScrollToIndexDemoPageState extends State<ScrollToIndexDemoPage> {
  // 滑动到指定位置，利用scroll_to_index包
  AutoScrollController scrollController;

  List<List<int>> scrollList;

  void initState() {
    super.initState();
    scrollController = AutoScrollController(
        viewportBoundaryGetter: () =>
            Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);
    scrollList = List.generate(100, (int index) {
      return List.generate(10, (int index1) {
        if (index1 == 0) {
          return index;
        } else {
          return math.Random().nextInt(100) + 100;
        }
      });
    });
  }

  // 滑动列表
  childrenList() {
    return scrollList.map<Widget>((data) {
      print(data);
      return Padding(
        padding: EdgeInsets.all(10),
        child: _wrapScrollTag(
            index: data[0],
            child: Container(
              height: data[1].toDouble(),
              alignment: Alignment.topCenter,
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.lightBlue, width: 4),
                  borderRadius: BorderRadius.circular(12)),
              child: Text(data[0].toString()),
            )),
      );
    }).toList();
  }

  Widget _wrapScrollTag({int index, Widget child}) => AutoScrollTag(
        index: index,
        controller: scrollController,
        child: child,
        key: ValueKey(index),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('滑动到指定位置1')),
      body: Container(
        child: ListView(
            scrollDirection: Axis.vertical,
            controller: scrollController,
            children: childrenList()),
      ),
      persistentFooterButtons: <Widget>[
        FlatButton(
            onPressed: () {
              scrollController.scrollToIndex(13,
                  preferPosition: AutoScrollPosition.begin);
            },
            child: Text('Scroll to 13'))
      ],
    );
  }
}
